<template>
  <div class="signUp">
    <div class="loading" v-if="loading">
      <div class="loading-icon">
        <mu-circular-progress class="demo-circular-progress" :size="36"></mu-circular-progress>
        <div class="font">上传中，请稍等</div>
      </div>
    </div>
    <div class="signUp-from">
      <!-- 上传照片 -->
      <div class="from-img">
        <div class="from-beforeimg">
          <div class="beforeimg uploadImg">
            <img src="../assets/before.png" class="beforeimg-img" alt="">
            <img :src="avatar1" alt="">
            <input class="change-photo-btn avatar1" type="file" accept="image/*" ref="inpFile" @change="upImg">
          </div>
        </div>
        <div class="from-afterimg uploadImg">
          <div class="afterimg">
            <img src="../assets/after.png"  class="beforeimg-img" alt="">
            <img :src="avatar2" alt="">
            <input class="change-photo-btn avatar2" type="file" accept="image/*" ref="inpFile2" @change="upImg">
          </div>
        </div>
      </div>
      
      <!-- 表单 -->
      <div class="from-contant">
        <input class="userNewName" v-model="userNewName" maxlength="6"  type="text" placeholder="请输入你的姓名" >
        <div class="store">
        <div class="store-input">
          <textarea rows="3" cols="20" maxlength="100" placeholder="（示例如下）
我叫XXX!我是XX地区的参赛禾粉，我的肌肤问题是XX，在禾葡兰的帮助下，如今的改善情况是XXXXXX，请大家投我一票！" ref="inputTextarea" v-model="store">
        </textarea>
        </div>
      </div>
        <!-- <div class="name">
          <font>姓名</font>
          <div class="name-input">
            <input type="text" placeholder="请输入姓名" ref="inputName" v-model="name">
          </div>
        </div> -->
        <!-- <div class="phone">
          <font>电话</font>
          <div class="phone-input">
            <input type="tel" placeholder="请输入电话" ref="inputPhone" v-model="mobile">
          </div>
        </div> -->
        <!-- <div class="Division">
          <font>赛区</font>
          <div class="Division-input">
            <select name="selectAge" id="selectAge" ref="inputDivision">
              <option v-for="address in addresses" :key="address.index">{{address.name}}</option>
            </select>
            <img src="http://sucai.suoluomei.cn/sucai_zs/images/select.png?x-oss-process=image/quality,Q_70" alt="">
          </div>
        </div> -->
        <!-- <div class="address">
          <font>地址</font>
          <div class="phone-input">
            <input type="text" placeholder="请输入地址" ref="inputAddress" v-model="addressed">
          </div>
        </div>
      </div> -->
      <!-- <div class="Division">
        <font>赛区</font>
        <div class="Division-input">
          <select name="selectAge" id="selectAge" ref="inputDivision">   
            <option v-for="address in addresses" :key="address.index">{{address.name}}</option>
          </select>
          <img src="http://sucai.suoluomei.cn/sucai_zs/images/select.png?x-oss-process=image/quality,Q_70" alt="">
        </div> -->
      </div>
      
      <div class="confirm">
        <button @click="confirm" v-if="baoming==1">修改</button>
        <button @click="confirm" v-else :disabled="disabled">我要报名</button>
      </div>
      <div class="jt">
        <img src="http://sucai.suoluomei.cn/sucai_zs/images/jts.png?x-oss-process=image/quality,Q_70" alt="">
      </div>
    </div>
    <!-- 底部导航 -->
    <bottomBar :toSelected='proValue' newText='报名' ></bottomBar>
    <mu-dialog title="提示" width="360" :open.sync="openSimple">
      {{contant}}
      <mu-button slot="actions" flat color="primary" @click="closeSimpleDialog">关闭</mu-button>
    </mu-dialog>
  </div>
</template>

<script>
import bottomBar from "../components/bottomBar.vue";
// import EventBus from "../eventBus"
import http from "../utils/http";
import EXIF from "exif-js/exif.js";
import util from "../utils/util.js";
import 'weui'
import weui from 'weui.js'
// import VConsole from "vconsole/dist/vconsole.min.js"

// new VConsole();
// url: 'http://ydnshop.hepulanerp.com/sucai_t/public/index.php/post/post/uploadFile',
const upImgUrl =
  "http://api110.herbplantist.com/sucai/public/index.php/post/post/uploadFile";
// const upImgUrl =
//   "http://api110.herbplantist.com/sucai/public/index.php/post/post/uploadFileFromWatermMrk";
// const uploadImgKey = 'Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO'
const uploadImgKey = "Gn1xVdBiTClSSHKZifg0pTQSU5XGagWO";

const prefix = "sign";
export default {
  name: "signUp",
  data() {
    return {
      proValue: "signUp",
      addresses: [],
      alert: false,
      alertValue: "",
      // 上传头像地址
      imgUrl: "",
      avatar1: require("../assets/zp.png"),
      avatar2: require("../assets/zp.png"),
      userNewName: '',
      store: localStorage.getItem(prefix + "store") || "",
      name: localStorage.getItem(prefix + "name") || "",
      mobile: localStorage.getItem(prefix + "mobile") || "",
      addressed: localStorage.getItem(prefix + "addressed") || "",
      baoming: 0,
      openSimple: false,
      contant: "",
      loading: false,
      upLoadflag: 0,
      disabled: false 
    };
  },
  watch: {
    name(name) {
      localStorage.setItem(prefix + "name", name);
    },
    mobile(mobile) {
      localStorage.setItem(prefix + "mobile", mobile);
    },
    addressed(addressed) {
      localStorage.setItem(prefix + "addressed", addressed);
    },
    store(store) {
      localStorage.setItem(prefix + "store", store);
    }
  },
  created() {
    var str = location.href;
    // console.log('urlStr',str)
    // var reg = /sign\/(.*)#/i
    // var res = str.search(reg)
    var start = str.search("sign/");
    var end = str.search("#");
    var start2 = parseInt(start + 5);
    var res = str.substring(start2, end);
    // console.log('res',res)
    var _this = this;
    http
      .post("Zmhf/index", {
        key: "be15d4ca913c91494cb4f9cd6ce317c6",
        sign: res,
        type: "SelectDivisionData"
      })
      .then(function(response) {
        response.data.forEach(item => _this.addresses.push(item));
        // console.log(_this.addresses);
        console.log(11)
        if (response.current_type == 2) {
          _this.$router.push({ path: "/personal" });
        }
      })
      .catch(function(error) {
        console.log(22)
        console.log('error', error.length)
/*        _this.openSimple = true;
        _this.contant = error;*/
      });
    // 编辑数据的接口
    http
      .post("Zmhf/index", {
        key: "be15d4ca913c91494cb4f9cd6ce317c6",
        sign: res,
        type: "DrawingBeautifulGrainData"
      })
      .then(function(response) {
        // console.log('编辑response',response);
        if (response.errcode == 0) {
          _this.avatar1 = response.data[0].before_image;
          _this.avatar2 = response.data[0].after_image;
          _this.baoming = response.is_sign;
          _this.store = response.data[0].content;
          _this.name = response.data[0].name;
          _this.mobile = response.data[0].mobile;
          _this.addressed = response.data[0].address;
        } else {
          _this.$weui.alert(response.msg);
        }
      })
      .catch(function(error) {
/*        _this.openSimple = true;
*//*        _this.contant = error;
*/      });
    //   EventBus.$on('LinkTo', function (data) {
    //   console.log(data)
    //   console.log(this.baoming)
    //   // this.baoming
    // })
  },
  methods: {

    confirm: function() {

      // console.log(1)
      // var name = this.$refs.inputName.value || '';
      // var phone = this.$refs.inputPhone.value || '';
      // var division = this.$refs.inputDivision.value || '';
      // var address = this.$refs.inputAddress.value || '';
      var store = this.$refs.inputTextarea.value || '';
      var img = this.avatar1;
      var img2 = this.avatar2;
      var userNewName = this.userNewName;
      if (img.trim() == "" || !img.includes("http") || !img2.includes("http")) {
        this.$weui.alert("请上传图片");
      } else if(this.userNewName.trim() == '') {
        this.$weui.alert("请输入姓名");
      }
      // else if (name == "") {
      //   this.openSimple = true;
      //   this.contant = "请输入姓名";
      // } else if (phone == "") {
      //   this.openSimple = true;
      //   this.contant = "请输入电话";
      // }
      // // else if (division == "") {
      // //   alert("请选择赛区");
      // // }
      // else if (address == "") {
      //   this.openSimple = true;
      //   this.contant = "请输入地址";
      // } 
      else if (store.trim() == "") {
        this.$weui.alert("请输入你的故事");
      } else {
        var str = location.href;
        // console.log('urlStr',str)
        // var reg = /sign\/(.*)#/i
        // var res = str.search(reg)
        var start = str.search("sign/");
        var end = str.search("#");
        var start2 = parseInt(start + 5);
        var res = str.substring(start2, end);
        // console.log('res',res)
        let that = this;
        this.disabled = true
        var loadingSubmit = weui.loading('报名提交中')
        http
          .post("Zmhf/index", {
            data: {
              // name: name,
              // mobile: phone,
              // division_id: division,
              // address: address,
              content: store,
              name: this.userNewName,
              before_image: this.avatar1,
              after_image: this.avatar2
            },
            key: "be15d4ca913c91494cb4f9cd6ce317c6",
            sign: res,
            type: "SaveDataBeautifulGrain"
          })
          .then(function(response) {
            // console.log("response", response);
            if (response.errcode == 0) {
              that.$weui.alert(response.msg);
              // console.log(response.data.candidates_id)
              that.$router.push({
                path: "/ticket",
                query: { candidates_id: response.data.candidates_id }
              });
              that.disabled = true
            }else if (response.errcode == 1) {
              that.$weui.alert(response.msg);
              that.disabled = false
            }
            // that.$router.go(0);
            loadingSubmit.hide()
          })
          .catch(function(error) {
            that.$weui.alert(error);
            loadingSubmit.hide()
          })
          .finally(function () {
            // that.disabled = false
          })
      }
    },
    upImg: function(event) {
      var _this = this;
      // 选择的文件对象
      var file = event.target.files[0];
      console.log('file',file)
      var orientation;
      //EXIF js 可以读取图片的元信息  https://github.com/exif-js/exif-js
      EXIF.getData(file, function() {
        orientation = EXIF.getTag(this, "Orientation");
      });

      // 压缩图片需要的一些元素和对象
      var fileReader = new FileReader(),
        img = new Image();

      // 缩放图片需要的canvas
      var canvas = document.createElement("canvas");
      var context = canvas.getContext("2d");

      // base64地址图片加载完毕后
      img.onload = function() {
        // 图片原始尺寸
        var originWidth = this.width;
        var originHeight = this.height;
        // 最大尺寸限制
        var maxWidth = 750,
          maxHeight = 1334;
        // 目标尺寸
        var targetWidth = originWidth,
          targetHeight = originHeight;

        var degree = 0,
          drawWidth,
          drawHeight,
          width,
          height;
        drawWidth = this.naturalWidth;
        drawHeight = this.naturalHeight;
        //以下改变一下图片大小
        var maxSide = Math.max(drawWidth, drawHeight);
        if (maxSide > 1024) {
          var minSide = Math.min(drawWidth, drawHeight);
          minSide = (minSide / maxSide) * 1024;
          maxSide = 1024;
          if (drawWidth > drawHeight) {
            drawWidth = maxSide;
            drawHeight = minSide;
          } else {
            drawWidth = minSide;
            drawHeight = maxSide;
          }
        }
        canvas.width = width = drawWidth;
        canvas.height = height = drawHeight;
        //判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
        switch (orientation) {
          //iphone横屏拍摄，此时home键在左侧
          case 3:
            degree = 180;
            drawWidth = -width;
            drawHeight = -height;
            break;
          //iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
          case 6:
            canvas.width = height;
            canvas.height = width;
            degree = 90;
            drawWidth = width;
            drawHeight = -height;
            break;
          //iphone竖屏拍摄，此时home键在上方
          case 8:
            canvas.width = height;
            canvas.height = width;
            degree = 270;
            drawWidth = -width;
            drawHeight = height;
            break;
        }

        // // 图片尺寸超过400x400的限制
        // if (originWidth > maxWidth || originHeight > maxHeight) {
        //   if (originWidth / originHeight > maxWidth / maxHeight) {
        //     // 更宽，按照宽度限定尺寸
        //     targetWidth = maxWidth
        //     targetHeight = Math.round(maxWidth * (originHeight / originWidth))
        //   } else {
        //     targetHeight = maxHeight
        //     targetWidth = Math.round(maxHeight * (originWidth / originHeight))
        //   }
        // }

        // // canvas对图片进行缩放
        // canvas.width = targetWidth
        // canvas.height = targetHeight
        // // 清除画布
        // context.clearRect(0, 0, targetWidth, targetHeight)
        // // 图片压缩
        // context.drawImage(img, 0, 0, targetWidth, targetHeight)
        //使用canvas旋转校正
        context.rotate((degree * Math.PI) / 180);
        context.drawImage(this, 0, 0, drawWidth, drawHeight);
        // canvas转为blob并上传
        console.log('canvas', canvas)

        canvas.toBlob(function(blob) {
          // 开始上传
          console.log("blob", blob);
          var formData = new FormData();
          formData.append("key", uploadImgKey);
          formData.append("file", blob, file.name);
          console.log(file.type);

          _this.showUploading = true;
          _this.loading = true;
          // 图片ajax上传
          _this.$axios
            .post(upImgUrl, formData, {
              headers: {
                "Content-Type": "multipart/form-data"
              }
            })
            .then(res => {
              // console.log
              if (Array.from(event.target.classList).includes("avatar1")) {
                _this.avatar1 = res.data.info.url + util.ossCompressHasWaterMark;
              }
              if (Array.from(event.target.classList).includes("avatar2")) {
                _this.avatar2 = res.data.info.url + util.ossCompressHasWaterMark;
              }
              _this.loading = false;
            })
            .catch(function(error) {
              _this.loading = false;
            });
        }, file.type || "image/png");
      };

      fileReader.onload = function(e) {
        img.src = e.target.result;
      };
      // 选择的文件是图片
      if (file.type.indexOf("image") == 0) {
        fileReader.readAsDataURL(file);
      }
    },

    closeSimpleDialog() {
      this.openSimple = false;
    },
    // 关闭弹窗
    closeAlert: function() {
      this.alert = false;
    }
  },
  components: { bottomBar }
};
</script>

<style lang="scss" scoped>
input[type="button"] {
  -webkit-appearance: none;
  outline: none;
}
.signUp {
  .loading {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 3000;
    .loading-icon {
      width: 100%;
      .font {
        display: block;
        width: 100%;
        color: #108ef3;
        font-weight: 500;
        font-size: 13px;
      }
    }
  }
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  height: 83rem;
  background-color: #f5f5f5;
  background-image: url("../assets/signUp-bgs.png");
  background-repeat: no-repeat;
  background-size: 100%;
  background-position: center;
  .signUp-from {
    margin-top: 9rem;
    width: 20rem;
    height: 43rem;
    .from-img {
      margin-top: 1rem;
      display: inline-flex;
      justify-content: space-around;
      width: 100%;
      .from-beforeimg {
        border-radius: 0.5rem;
        .change-photo {
          padding-top: 0.5rem;
          color: #ff0837;
        }
        .beforeimg {
          display: flex;
          justify-content: center;
          align-items: center;
          flex-wrap: wrap;
          position: relative;
          width: 9rem;
          height: 9rem;
          background-color: #fff;
          border-radius: 0.5rem;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
            border-radius: 0.5rem;
            vertical-align: bottom;
            object-fit: cover;
            &:nth-of-type(1) {
              position: absolute;
              top: 0;
              left: 0;
              width: 3rem;
              height: 3rem;
              border-top-left-radius: 0.5rem;
            }
          }
        }
        font {
          padding-top: 0.5rem;
          display: block;
          color: #ff8d8d;
        }
      }
      .from-afterimg {
        border-radius: 0.5rem;
        .afterimg {
          display: flex;
          justify-content: center;
          align-items: center;
          flex-wrap: wrap;
          position: relative;
          width: 9rem;
          height: 9rem;
          background-color: #fff;
          border-radius: 0.5rem;
          .addFont {
            width: 100%;
            font-size: 1rem;
            color: #ccc;
          }
          img {
            width: 100%;
            height: 100%;
            border-radius: 0.5rem;
            object-fit: cover;
            vertical-align: bottom;
            &:nth-of-type(1) {
              position: absolute;
              top: 0;
              left: 0;
              width: 3rem;
              height: 3rem;
              border-top-left-radius: 0.5rem;
            }
          }
        }
        font {
          padding-top: 0.5rem;
          display: block;
          color: #ff8d8d;
        }
      }
      .uploadImg {
        background-size: cover;
        background-repeat: no-repeat;
        background-position: 50% 50%;
        .change-photo {
          color: #ff8d8d;
        }
        input {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          opacity: 0;
          outline: 0;
        }
      }
    }
    .from-contant {
      margin-top: 1rem;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      width: 100%;
      .name,
      .phone,
      .Division,
      .address {
        margin-top: 1rem;
        display: inline-flex;
        justify-content: space-between;
        align-items: center;
        width: 90%;
        font {
          display: block;
          width: 4rem;
          color: #000;
          font-size: 0.9rem;
          text-align: left;
        }
        .name-input,
        .phone-input,
        .address-input {
          padding: 0.05rem 0.1rem;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 15rem;
          height: 2rem;
          line-height: 2rem;
          border-radius: 0.2rem;
          border: #ff0837 0.1rem solid;
          background-size: cover;
          background-position: center;
          color: #555;
          input {
            width: 100%;
            height: 100%;
            border: 0;
            border-radius: 0.2rem;
            outline: none;
            text-align: center;
            background-color: #fff;
          }
        }
        .Division-input {
          position: relative;
          padding: 0.05rem 0.1rem;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 15rem;
          height: 2rem;
          line-height: 2rem;
          border-radius: 0.2rem;
          border: #ff0837 0.1rem solid;
          background-size: cover;
          background-position: center;
          select {
            -webkit-appearance: none;
            padding-left: 4.2rem;
            width: 100%;
            height: 100%;
            border: 0;
            border-radius: 0.2rem;
            outline: none;
            text-align: center;
            background-color: #fff;
            color: #555;
          }
          img {
            position: absolute;
            right: 0.5rem;
            width: 0.7rem;
          }
        }
      }
    }
    .userNewName {
      text-align: center;
      font-size: 0.9rem;
      padding: 0.3rem 0;  
        border-radius: 0.4rem;
        border: #ff0837 0.1rem solid;
      width: 10rem; 
    }
    .store {
      margin-top: 1rem;
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 90%;
      font {
        font-size: 0.9rem;
      }
      .store-input {
        padding: 0.05rem 0.08rem;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 20rem;
        height: 7rem;
        border-radius: 0.2rem;
        border: #ff0837 0.1rem solid;
        background-size: cover;
        background-position: center;
        textarea {
          width: 100%;
          height: 100%;
          border: 0;
          border-radius: 0.2rem;
          outline: none;
          text-align: center;
        }
      }
    }
    .confirm {
      margin-top: 1rem;
      width: 100%;
      display: flex;
      justify-content: center;
      button {
        width: 8rem;
        height: 3rem;
        color: #fff;
        font-size: 1rem;
        border: 0;
        border-radius: 1rem;
        background-image: url('http://sucai.suoluomei.cn/sucai_zs/images/btn.png?x-oss-process=image/quality,Q_70');
        background-size: 100% 100%;
        background-position: center;
        background-repeat: no-repeat;
      }
    }
    .jt{
      margin-top: 1rem;
      width: 100%;
      img{
        width: 40%;
      }
    }
  }
}
</style>
